# 第三方库
from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user

# 本地模块
from admin.admin.admin_class import UserForm
from inc.models import AdminUser, AdminMember, OperationLog, db


admin_user_bp = Blueprint('admin_user', __name__)

@admin_user_bp.route('/users')
@login_required

def user_management():
    users = AdminUser.query.all()
    members = AdminMember.query.all()
    return render_template('admin/admin/admin_user.html', users=users, members=members)


# 在 admin/admin_user.py 中修改用户管理路由

@admin_user_bp.route('/users/add', methods=['GET', 'POST'])
@login_required

def add_user():
    form = UserForm()

    # 移除角色选项加载
    if form.validate_on_submit():
        try:
            user = AdminUser(
                username=form.username.data,
                real_name=form.real_name.data,
                is_super=form.is_super.data,
                member_id=form.member_id.data if form.member_id.data != 0 else None
            )

            # 设置密码
            if form.password_hash.data:
                user.password = form.password_hash.data

            # 移除角色分配
            db.session.add(user)

            # 记录操作日志
            OperationLog.create(
                admin_id=current_user.id,
                action="添加用户",
                resource="AdminUser",
                details=f"添加用户: {form.username.data}",
                success=True,
                ip_address=request.remote_addr
            )

            db.session.commit()
            flash('用户已添加', 'success')
            return redirect(url_for('admin.admin_user.user_management'))
        except Exception as e:
            db.session.rollback()
            flash(f'添加用户时出错: {str(e)}', 'danger')

    return render_template('admin/admin/admin_useradd.html', form=form, title='添加用户')


@admin_user_bp.route('/users/edit/<int:id>', methods=['GET', 'POST'])
@login_required

def edit_user(id):
    user = AdminUser.query.get_or_404(id)
    form = UserForm(obj=user)

    # 移除角色默认值设置
    # 设置员工默认值
    form.member_id.data = user.member_id or 0

    # 移除密码验证
    form.password_hash.validators = []

    if form.validate_on_submit():
        try:
            user.username = form.username.data
            user.real_name = form.real_name.data
            user.is_super = form.is_super.data
            user.member_id = form.member_id.data if form.member_id.data != 0 else None

            # 更新密码
            if form.password_hash.data:
                user.password = form.password_hash.data

            # 移除角色更新
            # 记录操作日志
            OperationLog.create(
                admin_id=current_user.id,
                action="编辑用户",
                resource="AdminUser",
                details=f"更新用户: {user.username}",
                success=True,
                ip_address=request.remote_addr
            )
            db.session.commit()
            flash('用户已更新', 'success')
            return redirect(url_for('admin.admin_user.user_management'))
        except Exception as e:
            db.session.rollback()
            flash(f'更新用户时出错: {str(e)}', 'danger')

    form.password_hash.data = ''
    return render_template('admin/admin/admin_useradd.html', form=form, title='编辑用户', user=user)



@admin_user_bp.route('/change_password', methods=['GET', 'POST'])
@login_required
def change_password():
    if request.method == 'POST':
        current_password = request.form.get('current_password')
        new_password = request.form.get('new_password')
        confirm_password = request.form.get('confirm_password')

        if not current_user.verify_password(current_password):
            flash('当前密码不正确', 'danger')
            return redirect(url_for('admin.admin_user.change_password'))

        if new_password != confirm_password:
            flash('新密码与确认密码不匹配', 'danger')
            return redirect(url_for('admin.admin_user.change_password'))

        current_user.password = new_password
        db.session.commit()
        flash('密码修改成功', 'success')
        return redirect(url_for('admin.dashboard'))

    return render_template('admin/admin/admin_password.html')

@admin_user_bp.route('/users/delete/<int:id>')
@login_required

def delete_user(id):
    user = AdminUser.query.get_or_404(id)
    if user.id == current_user.id:
        flash('不能删除当前登录的用户', 'danger')
        return redirect(url_for('admin.admin_user.user_management'))
    try:
        db.session.delete(user)
        log = OperationLog(
            admin_id=current_user.id,
            action="删除用户",
            resource="AdminUser",
            details=f"删除用户: {user.username}",
            success=True,
            ip_address=request.remote_addr
        )
        db.session.add(log)
        db.session.commit()
        flash('用户已删除', 'success')
    except Exception as e:
        db.session.rollback()
        flash(f'删除用户时出错: {str(e)}', 'danger')
    return redirect(url_for('admin.admin_user.user_management'))